<template>
  <div id="container">
    <div class="login_box">
      <el-form
        :model="registerForm"
        :rules="rules"
        ref="Register"
        :label-position="labelPosition"
        label-width="82px"
      >
        <!-- 基本注册信息 -->
        <h3 class="login_title">欢迎注册</h3>
        <el-form-item label="用户名:" prop="user_name"
          ><el-input
            placeholder="请设置用户名"
            v-model.trim="registerForm.user_name"
          ></el-input
        ></el-form-item>
        <el-form-item label="密码:" prop="user_password"
          ><el-input
            placeholder="请设置密码"
            v-model.trim="registerForm.user_password"
            show-password
          ></el-input
        ></el-form-item>
        <el-form-item label="确认密码:" prop="confirmuser_password"
          ><el-input
            placeholder="请再次确认密码"
            show-password
            v-model.trim="registerForm.confirmuser_password"
          ></el-input
        ></el-form-item>

        <!-- 验证码部分 -->
        <el-form-item label="验证码:" prop="input_IdentifyCode">
          <div id="identify_part">
            <el-input
              v-model.trim="registerForm.input_IdentifyCode"
              placeholder="请输入验证码"
            ></el-input>
            <div
              @click="refreshCode()"
              class="code"
              style="cursor: pointer"
              title="点击切换验证码"
            >
              <identify :identifyCode="identifyCode"></identify>
            </div>
          </div>
        </el-form-item>

        <!-- 注册按钮组 -->
        <el-button type="primary" @click="submitForm">立即注册 </el-button>
        <div class="login_bottom_box">
          <router-link to="/login" @click="goLogin"
            >已有账号？去登录</router-link
          >
        </div>
      </el-form>
    </div>

    <!-- 注册成功提示框 -->
    <!-- dialogVisible默认为false，submitForm成功后，转为ture -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%"
      ><span>用户注册成功！请跳转登录?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="goLogin" id="now_login"
          >现在登录</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Identify from './components/Identify.vue'
export default {
  name: 'register',
  components: { Identify },
  data() {
    // 判断用户名事发后含有特殊字符
    var validateInput = (rule, value, callback) => {
      if (!this.checkSpecialKey(value)) {
        callback(new Error('不能含有特殊字符/、*、-、`、#'))
      } else if (this.checkuser_name()) {
        callback(new Error('该用户名已存在，请重新输入'))
      } else {
        callback()
      }
    }
    // 判断密码
    var validateConfirmuser_password = (rule, value, callback) => {
      if (!this.checkConfirmuser_password()) {
        // this.makeCode();
        this.refreshCode()
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    // 判断验证码正误
    var validateIdentifyCode = (rule, value, callback) => {
      if (!this.checkIdentifyCode()) {
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }

    return {
      registerForm: {
        user_name: '',
        user_password: '',
        confirmuser_password: '',
        input_IdentifyCode: '',
      },
      // 要求
      rules: {
        user_name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            type: 'string',
            message: '请输入正确的用户名',
            trigger: ['blur', 'change'],
          },
          { min: 2, max: 7, message: '长度在2~7个字符', trigger: 'blur' },
          { validator: validateInput, trigger: ['blur', 'change'] },
        ],
        user_password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在6~10个字符', trigger: 'blur' },
          { validator: validateInput, trigger: ['blur', 'change'] },
        ],
        confirmuser_password: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmuser_password, trigger: ['blur'] },
        ],
        input_IdentifyCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: validateIdentifyCode, trigger: ['blur'] },
        ],
      },
      labelPosition: 'right',
      users: [],
      dialogVisible: false,
      identifyCode: '',
      identifyCodes: [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
      ], //根据实际需求加入自己想要的字符
    }
  },
  created() {
    this.getAllUsers()
  },
  mounted() {
    this.refreshCode()
  },
  methods: {
    // 获取全部用户
    getAllUsers() {
      // 获取所有用户数据
      this.$http.get('/gg_user').then((res) => {
        this.users = res.result
      })
    },
    // 特殊字符
    checkSpecialKey(str) {
      let specialKey = '[/,*,-,`,#]'
      for (let i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) != -1) {
          return false
        }
      }
      return true
    },
    // 用户名重复
    checkuser_name() {
      var check = this.users.find(
        (item) => item.user_name == this.registerForm.user_name
      )
      if (check) {
        return true
      } else {
        return false
      }
    },
    // 重复密码
    checkConfirmuser_password() {
      if (
        this.registerForm.confirmuser_password ===
        this.registerForm.user_password
      ) {
        return true
      }
      return false
    },
    // 验证码相关
    checkIdentifyCode() {
      if (this.registerForm.input_IdentifyCode === this.identifyCode) {
        return true
      } else {
        return false
      }
    },
    // 注册按钮
    submitForm() {
      // 进行登录验证
      this.$refs['Register'].validate((valid) => {
        // 1.表单验证通过
        if (valid) {
          // 1.提示相关信息
          console.log('验证成功')
          // 2.新增用户至数据库
          this.$http
            .post('/gg_user', {
              user_name: this.registerForm.user_name,
              user_password: this.registerForm.user_password,
            })
            .then((res) => {
              console.log('成功', res)
              // 注册成功,
              // 3.1则弹出提示框, 选择返回登录页面
              // 3.2清空表单数据
              if (res.code == 0) {
                this.$refs['Register'].resetFields()
                this.dialogVisible = true
              }
            })
        } else {
          // 2.表单验证不同过, 提示
          this.$message({
            type: 'error',
            message: '请按提示进行修改后注册',
            duration: 900,
          })
        }
      })
    },
    // 已有账号登录
    goLogin() {
      this.dialogVisible = false
      this.$refs['Register'].resetFields()
      this.$router.push('/login')
    },
    // 生成随机数
    randomNum(min, max) {
      max = max + 1
      return Math.floor(Math.random() * (max - min) + min)
    },
    // 更新验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
      console.log('当前验证码:', this.identifyCode)
    },
    // 随机生成验证码字符串
    makeCode(data, len) {
      console.log('data, len:', data, len)
      for (let i = 0; i < len; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length - 1)]
      }
    },
  },
}
</script>

<style>
body {
  background: url('../assets/image/bg.png');
}
#container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  padding: 0px;
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 100%;
}
#container .login_box {
  width: 400px;
  border-radius: 24px;
  background: rgba(255, 255, 255, 0.4);

  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.el-form {
  padding: 20px 22px;
  box-sizing: border-box;
  overflow: hidden;
}
.el-form .login_title {
  width: 100%;
  display: inline-block;
  margin: 0 auto 30px auto;
  color: black;
  font-size: 36px;
  font-weight: 700px;
  font-family: '微软雅黑';
}

.el-form-item:nth-last-child(2) {
  margin-bottom: 10px;
}
.el-form-item:last-child {
  margin-bottom: 0px;
}
.el-form .el-button {
  width: 97%;
  margin: 10px 10px;
  font-size: 18px;
  background: #5073d8;
  border-color: #5073d8;
  border-radius: 20px;
}
.el-form .login_bottom_box {
  display: flex;
  justify-content: space-between;
  width: 97%;

  margin: 15px 10px 0 10px;
}
.el-form .login_bottom_box a {
  display: inline-block;
  margin: 0 auto;
  color: #5073d8;
  text-align: center;
  cursor: pointer;
}
.el-form .login_bottom_box a:hover {
  color: rgb(8, 239, 212);
}
#now_login {
  background: #5073d8;
  border-color: #5073d8;
}

#identify_part {
  display: flex;
  justify-content: space-between;
}
#identify_part .el-input {
  flex: 0.9;
}
</style>
